# core/translation_engine.py

import logging
from typing import Dict, List
from core.config import settings
from core.translation_interface import TranslationEngine  # 导入新的统一接口
from datetime import datetime
import re

logger = logging.getLogger(__name__)

# 联合国六种官方语言代码
UN_LANGUAGES = ['zh', 'en', 'fr', 'ru', 'es', 'ar']

# 源语言检测关键词映射
LANG_DETECTION_MAP = {
    'zh': ['你好', '测试', '文本', '世界'],
    'en': ['hello', 'world', 'test', 'this is'],
    'fr': ['bonjour', 'ceci', 'français', 'test'],
    'es': ['hola', 'español', 'prueba', 'esto'],
    'ru': ['здра', 'тест', 'привет', 'руский'],
    'ar': ['مرحبا', 'العالم', 'اختبار', 'عربي']
}

# 模拟翻译映射表
SIMULATED_RESPONSES = {
    'zh': '你好，这是一个测试。Hello, this is a test transcription.',
    'en': 'Hello, this is a test transcription. 你好，这是测试文本。',
    'fr': 'Bonjour, ceci est une transcription de test. 你好，这是测试文本。',
    'es': 'Hola, esta es una transcripción de prueba. 你好，这是测试文本。',
    'ru': 'Здравствуйте, это тестовая транскрипция. 你好，这是测试文本。',
    'ar': 'مرحباً، هذا نص اختباري. Hello, this is a test transcription.'
}


class MockTranslationEngine(TranslationEngine):
    """
    模拟翻译引擎，用于开发和测试
    实现统一的翻译接口
    """
    def __init__(self):
        self._is_loaded = False
        self.supported_langs = getattr(settings, "SUPPORTED_LANGUAGES", UN_LANGUAGES)
        self.load_model()

    def load_model(self):
        logger.info(f"模拟加载翻译模型: {getattr(settings, 'TRANSLATION_MODEL_PATH', 'mock-model-path')}")
        self._is_loaded = True

    def _detect_language(self, text: str) -> str:
        text_lower = text.lower()
        for lang, keywords in LANG_DETECTION_MAP.items():
            if any(k.lower() in text_lower for k in keywords):
                return lang
        return "en"  # 默认英文

    def translate_text(
        self, 
        text: str, 
        source_lang: str = "auto", 
        target_lang: str = "en"
    ) -> Dict:
        """
        文本翻译接口
        
        Args:
            text: 源文本
            source_lang: 源语言，'auto' 表示自动检测
            target_lang: 目标语言
            
        Returns:
            Dict: 包含翻译结果的字典
        """
        if not text.strip():
            raise ValueError("文本不能为空")

        if target_lang not in self.supported_langs:
            raise ValueError(f"不支持的目标语言: {target_lang}，支持的语言: {self.supported_langs}")

        detected_source = self._detect_language(text) if source_lang == "auto" else source_lang
        translated = SIMULATED_RESPONSES.get(target_lang, f"[{target_lang.upper()}] {text}")

        return {
            "source_text": text,
            "translated_text": translated,
            "source_lang": detected_source,
            "target_lang": target_lang,
            "confidence": 0.95,  # 模拟置信度
            "engine": "mock-translation-engine",
            "timestamp": datetime.now().isoformat(timespec='seconds')
        }

    def translate_audio(
        self, 
        audio_path: str, 
        source_lang: str = "auto",
        target_lang: str = "en",
        enable_translation: bool = True,
        return_segments: bool = False
    ) -> Dict:
        """
        音频翻译接口（模拟实现）
        
        Args:
            audio_path: 音频文件路径
            source_lang: 源语言，'auto' 表示自动检测
            target_lang: 目标语言
            enable_translation: 是否启用翻译
            return_segments: 是否返回分段信息
            
        Returns:
            Dict: 包含翻译结果的字典
        """
        if not audio_path:
            raise ValueError("音频路径不能为空")

        # 模拟音频处理
        detected_source = source_lang if source_lang != "auto" else "zh"
        source_text = "你好，这是一个测试音频。Hello, this is a test audio."
        
        if enable_translation:
            translated_text = SIMULATED_RESPONSES.get(target_lang, f"[{target_lang.upper()}] {source_text}")
        else:
            translated_text = source_text

        result = {
            "source_text": source_text,
            "translated_text": translated_text,
            "source_lang": detected_source,
            "target_lang": target_lang,
            "confidence": 0.92,
            "duration": 5.5,  # 模拟音频时长
            "engine": "mock-translation-engine",
            "timestamp": datetime.now().isoformat(timespec='seconds'),
            "segments": []
        }

        # 添加模拟分段信息
        if return_segments:
            result["segments"] = [
                {"id": 0, "start": 0.0, "end": 2.5, "text": "你好，这是一个测试音频。"},
                {"id": 1, "start": 2.5, "end": 5.5, "text": "Hello, this is a test audio."}
            ]

        logger.info(f"模拟音频翻译完成: {audio_path}")
        return result

    def batch_translate_text(self, texts: List[str], source_lang: str = "auto", target_lang: str = "en") -> List[Dict]:
        """批量文本翻译"""
        results = []
        for text in texts:
            try:
                result = self.translate_text(text, source_lang, target_lang)
                results.append(result)
            except Exception as e:
                logger.error(f"批量翻译失败，文本: {text[:30]}..., 错误: {e}")
                # 返回错误结果
                results.append({
                    "source_text": text,
                    "translated_text": f"[翻译失败: {str(e)}]",
                    "source_lang": source_lang,
                    "target_lang": target_lang,
                    "confidence": 0.0,
                    "engine": "mock-translation-engine",
                    "timestamp": datetime.now().isoformat(timespec='seconds')
                })
        return results

    def get_supported_languages(self) -> Dict[str, list]:
        """获取支持的语言列表"""
        return {
            "source_languages": ["auto"] + self.supported_langs,
            "target_languages": self.supported_langs,
            "detection_supported": True
        }

    def is_ready(self) -> bool:
        return self._is_loaded

    # 兼容性方法（向后兼容）
    def translate(self, text: str, source_lang: str = "auto", target_lang: str = "en") -> Dict:
        """兼容方法：调用 translate_text"""
        return self.translate_text(text, source_lang, target_lang)

    def batch_translate(self, texts: List[str], target_lang: str) -> List[str]:
        """兼容方法：批量翻译，返回翻译后的文本列表"""
        results = self.batch_translate_text(texts, "auto", target_lang)
        return [result["translated_text"] for result in results]

    def supported_languages(self) -> List[str]:
        """兼容方法：返回支持的语言列表"""
        return self.supported_langs.copy()


# ========================================================
# 全局翻译引擎实例（工厂模式 + 延迟加载）
# ========================================================

translation_engine: TranslationEngine = None

# 优先使用Whisper Transformers引擎
if getattr(settings, 'USE_WHISPER_TRANSFORMERS', False):
    try:
        from core.whisper_transformers_engine import WhisperTransformersEngine
        model_path = str(getattr(settings, 'WHISPER_TRANSFORMERS_MODEL_PATH', 'models/whisper-base'))
        translation_engine = WhisperTransformersEngine(model_path=model_path)
        logger.info(f"使用Whisper Transformers引擎: {model_path}")
    except Exception as e:
        logger.error(f"加载Whisper Transformers引擎失败: {e}")
        # 回退到其他引擎
        if settings.USE_REAL_TRANSLATION_MODEL:
            try:
                from core.real_translation_engine import RealTranslationEngine
                translation_engine = RealTranslationEngine()
                logger.info("回退到真实翻译模型 (faster-whisper)")
            except Exception as e2:
                logger.error(f"加载真实翻译模型失败，回退到 Mock 模式: {e2}")
                translation_engine = MockTranslationEngine()
        else:
            translation_engine = MockTranslationEngine()
            logger.info("回退到 Mock 翻译模式")
elif settings.USE_REAL_TRANSLATION_MODEL:
    try:
        # 延迟导入：只在需要时导入 RealTranslationEngine
        from core.real_translation_engine import RealTranslationEngine
        translation_engine = RealTranslationEngine()
        logger.info("使用真实翻译模型 (faster-whisper)")
    except Exception as e:
        logger.error(f"加载真实翻译模型失败，回退到 Mock 模式: {e}")
        translation_engine = MockTranslationEngine()
else:
    translation_engine = MockTranslationEngine()
    logger.info("使用 Mock 翻译模式（用于开发测试）")

# 可选：添加日志确认
logger.info(f"翻译引擎已就绪: {translation_engine.__class__.__name__}")